package com.sikadwafastdaisfondturbo.pretloan.ui.user.activity

import android.annotation.SuppressLint
import android.graphics.Paint
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sikadwa.analysis.util.GoogleInstallUtil
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.AmountAdapter
import com.sikadwafastdaisfondturbo.pretloan.analysis.TestAnalysisAddEvent
import com.sikadwafastdaisfondturbo.pretloan.analysis.TestAnalysisInit
import com.sikadwafastdaisfondturbo.pretloan.databinding.ActivityUserLoginBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.PrivacyPolicyActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.credit.activity.CreditActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.BarUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.DensityUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.SmsCodeDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.ActivityStackHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import com.sikadwafastdaisfondturbo.pretloan.utils.rv.LinearDecoration
import com.sikadwafastdaisfondturbo.pretloan.utils.thread.TimingThread
import org.json.JSONObject


/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/21 19:28
 * @Annotation：用户登录
 */
class UserLoginActivity: ProActivity(), TimingThread.ITimingThreadListener  {
    lateinit var binding: ActivityUserLoginBinding
    var mAmountAdapter: AmountAdapter? = null

    //倒计时
    var count = 60
    private var timeThread: TimingThread? = null
    var mSmsDialog: SmsCodeDialog? = null
    override fun getRootView(): View {
        binding = ActivityUserLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        //关闭当前页面以外的所有页面
        ActivityStackHelper.finishAllActivity(UserLoginActivity::class.java)

        binding.parentLayout.setPadding(0,BarUtils.getStatusBarHeight(),0,0)

        initRvAmount()
        checkNextState()

        val stringAccept = String.format(getString(R.string.login_accept),getString(R.string.app_name))
        val stringPrivacy = getString(R.string.login_privacy_policy)
        val stringShow = "$stringAccept $stringPrivacy"
        val spString = SpannableString(stringShow)
        val start = stringShow.indexOf(stringPrivacy)
        val end = start + stringPrivacy.length
        spString.setSpan(ForegroundColorSpan(getColor(R.color.FFFF8378)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //下划线
        spString.setSpan(UnderlineSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textPrivacy.text = spString
        // 确保TextView可以接收点击事件
        binding.textPrivacy.movementMethod = LinkMovementMethod.getInstance();

        //时区区号
        binding.textCode.text = "+${Configs.getSPString(Configs.SPKEY.SIKADWA_TIMEZONE_CODE)}"
        binding.textCode.paint.flags = Paint.UNDERLINE_TEXT_FLAG//下划线
        binding.textCode.paint.isAntiAlias = true//抗锯齿
    }

    override fun initListener() {
        //客服
        binding.imgKefu.setOnClickListener {
            showKefuDialog("Login Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"Login Page")
        }
        //电话号码入框监听
        binding.editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextState()
            }
        })
        binding.editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editText.clearFocus()
                true
            }
            false
        }
        //电话号码输入框焦点监听
        binding.editText.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                addEvent(EventType.FORM.FORM_LOGIN_MOBILE, getEditMobile())
            }
        }

        //隐私政策切换
        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
            checkNextState()
            when (isChecked) {
                true -> {
                    addEvent(EventType.CLICK.CLICK_LOGIN_PRIVACY_AGREE, "")
                }

                false -> {
                    addEvent(EventType.CLICK.CLICK_LOGIN_PRIVACY_DENY, "")
                }
            }
        }

        //Next
        binding.btnNext.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_LOGIN_NEXT, "")
            binding.editText.clearFocus()
            //发送验证码
            showLoading()
            sendSMSAction()
        }

        // Privacy policy
        binding.textPrivacy.setOnClickListener {
            onIntent(PrivacyPolicyActivity::class.java)
        }
    }

    override fun initData() {
        val amountList = arrayListOf<String>()
        val amountString = getAmount()
        for (i in amountString.indices){
            amountList.add(amountString[i].toString())
        }
        mAmountAdapter!!.data = amountList
    }

    private fun initRvAmount(){
        binding.rvAmount.setHasFixedSize(true)
        binding.rvAmount.isNestedScrollingEnabled = false
        binding.rvAmount.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(14f)
        binding.rvAmount.addItemDecoration(LinearDecoration(0,decoration,0,0))
        val layoutManager = LinearLayoutManager(getContext())
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.rvAmount.layoutManager = layoutManager
        mAmountAdapter = AmountAdapter(binding.rvAmount)
        mAmountAdapter!!.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mAmountAdapter!!.getItem(position)
        }
        binding.rvAmount.adapter = mAmountAdapter
    }

    /**
     * 设置按钮状态
     */
    private fun checkNextState() {
        if (binding.checkBox.isChecked && getEditMobile().isNotEmpty()) {
            binding.btnNext.alpha = 1f
            binding.btnNext.isEnabled = true
        } else {
            binding.btnNext.alpha = 0.2f
            binding.btnNext.isEnabled = false
        }
    }

    /**
     * 获取默认账号
     */
    private fun getAmount(): String {
        var homeAmount = "300000"
        val data = getCommonObject()
        val customizeObj = data.optJSONObject("customize")
        if (customizeObj != null) {
            homeAmount = customizeObj.optString("homeAmount", "300000")
        }
        return homeAmount
    }

    /**
     * 获取手机号码内容
     */
    private fun getEditMobile(): String {
        return binding.editText.text.toString().trim()
    }

    /**
     * 验证码输入框
     */
    private fun showSMSCodeDialog() {
        if (mSmsDialog == null) {
            mSmsDialog = SmsCodeDialog(this, object : SmsCodeDialog.IDialogCallback {
                //点击操作监听
                override fun onClick(view: View?) {
                    when (view!!.id) {
                        R.id.imgClose -> {//关闭
                            if (timeThread != null) {
                                timeThread!!.stopThread()
                            }
                            mSmsDialog!!.dismiss()
                        }

                        R.id.btnGetCode -> {//重发
                            sendSMSAction()
                            addEvent(EventType.CLICK.CLICK_LOGIN_VERIFY_CODE_RESEND, "")
                        }
                    }
                }

                //输入完成监听
                override fun inputComplete(content: String) {
                    addEvent(EventType.FORM.FORM_LOGIN_VARIFY_CODE, content)
                    loginAction(content,"NO")
                }
            })
            mSmsDialog!!.setCancelable(false)
            mSmsDialog!!.setCanceledOnTouchOutside(false)
        }
        if (!mSmsDialog!!.isShowing) {
            mSmsDialog!!.show()
            mSmsDialog!!.showCountdownView(count)
        }
        startTimeThread()
    }

    /**
     * 启动倒计时
     */
    private fun startTimeThread() {
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        count = 60
        mSmsDialog!!.showCountdownView(count)
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread!!.setThreadDelayMillis(1000)
            timeThread!!.setLoadListener(this)
        }
        timeThread!!.startThread()
    }

    override fun onLoading() {
        if (count <= 1) {
            count = 60
            timeThread!!.stopThread()
            mSmsDialog!!.showGetCodeView()
            return
        }
        count--
        mSmsDialog!!.refreshCountdown(count)
    }

    /**
     * 获取是否是审核账号信息
     */
    private fun checkUncleConfigAccount(): JSONObject?{
        //发送验证码之前，需要验证手机号是否在 app配置 accList里存在
        val commonData = getCommonObject()
        val customize = commonData.optJSONObject("customize")
        var accItem: JSONObject? = null
        if (customize != null){
            val accList = customize.optJSONArray("accList")
            if (accList != null && accList.length() > 0){
                for (i in 0..<accList.length()){
                    val obj = accList.optJSONObject(i)
                    if (getEditMobile() == obj.optString("accM")){
                        accItem = obj
                        break
                    }
                }
            }
        }
        return accItem
    }

    /**
     * 登录成功
     */
    private fun onLoginSuccess(uid: String, token: String){
        //保存手机号码，个人中心使用
        Configs.saveSPString(Configs.SPKEY.SIKADWA_MOBILE, getEditMobile())
        //保存用户登录状态为已登录
        Configs.saveSPBoolean(Configs.SPKEY.SIKADWA_LOGIN,true)
        //保存用户id
        Configs.saveSPString(Configs.SPKEY.SIKADWA_USERID,uid)
        //保存用户Token
        Configs.saveSPString(Configs.SPKEY.SIKADWA_TOKEN,token)
        //初始化analysis lib 赋值 用户id 和 token
        TestAnalysisInit.initAnalysisLibAtLoginSuccess()

        hideLoading()
        onLoginSuccess()
    }

    /**
     * 登录成功
     */
    private fun onLoginSuccess() {
        //停止倒计时
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        if (mSmsDialog != null) {
            onHideSoftInput(mSmsDialog!!.binding.editText)
            mSmsDialog!!.dismiss()
        }
        onIntent(CreditActivity::class.java)
        finish()
    }

    /**
     * 发送验证码
     */
    private fun sendSMSAction(){
        //发送验证码之前，需要验证手机号是否在 app配置 accList里存在
        val accItem = checkUncleConfigAccount()
        //accList 存在该手机号，直接进入登录成功流程
        if (accItem != null){
            Configs.saveSPBoolean(Configs.SPKEY.SIKADWA_IS_CONFIG_ACCOUNT,true)
            onLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
            return
        }
        Configs.saveSPBoolean(Configs.SPKEY.SIKADWA_IS_CONFIG_ACCOUNT,false)
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path",AppUrls.PATH.SEND_SMS)
            put("mobile",getEditMobile())
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //是否直接登录
                val directLoginFlag = obj?.optString("directLoginFlag", "NO")
                if (directLoginFlag == "YES"){
                    //直接执行登录接口  code: 0000
                    loginAction("0000",directLoginFlag)
                    return
                }
                showSMSCodeDialog()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }

    /**
     * 登录
     */
    private fun loginAction(code: String,directLoginFlag: String){
        //登录之前，需要验证手机号是否在 app配置 accList里存在
        val accItem = checkUncleConfigAccount()
        //accList 存在该手机号，直接进入登录成功流程
        if (accItem != null){
            Configs.saveSPBoolean(Configs.SPKEY.SIKADWA_IS_CONFIG_ACCOUNT,true)
            onLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
            return
        }
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path",AppUrls.PATH.LOGIN)
            put("mobile",getEditMobile())//手机号
            put("code",code)//验证码
            put("channelCode", GoogleInstallUtil.getInstallReferrer())//渠道号
            put("subChannelCode", GoogleInstallUtil.getInstallReferrer())//子渠道号
            put("directLoginFlag",directLoginFlag)//是否直接登录
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    val userId = obj.optString("userId","")
                    val userToken = obj.optString("token","")
                    val type = obj.optString("type")

                    //登录类型 == 注册，需要打点
                    if (type == "REGISTER"){
                        TestAnalysisAddEvent.addRegisterEvent()
                    }
                    onLoginSuccess(userId,userToken)
                }
            }

            override fun onRequestError(error: JSONObject) {
//                //停止倒计时
//                if (timeThread != null) {
//                    timeThread!!.stopThread()
//                }
                if (mSmsDialog != null) {
                    //显示验证码错误样式
                    mSmsDialog!!.showWrongView()
                }
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_LOGIN_START, "")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_LOGIN_END, "")
        if (timeThread != null) {
            timeThread!!.stopThread()
            timeThread = null
        }
        if (mSmsDialog != null) {
            mSmsDialog = null
        }
    }
}